package tp.pr1;

public class RobotEngine {
	
	/**
	 * 
	 * @param initialPlace sitio desde donde se parte
	 * @param direction	dirección inicial
	 * @param cityMap mapa de la ciudad
	 */
	public RobotEngine (Place initialPlace, Direction direction, Street[] cityMap) {
		this.position = initialPlace;
		this.direction = direction;
		this.cityMap = cityMap;
	}
	
	/**
	 * Mueve al robot en caso de que se pueda hacia la siguiente dirección
	 */
	private void move() {
		boolean a = false;
		//recorremos todo el bucle que terminamos al encontrar lo que buscábamos
		boolean salir = false;
		for (int i = 0; i < cityMap.length && !salir; i++) {
			if (this.cityMap[i].comeOutFrom(this.position,this.direction)) {
				a = true;
				this.position = cityMap[i].nextPlace(this.position);
				System.out.println(this.direction.moveDirection());
				System.out.println(this.position.toString());
				System.out.println(this.direction.sayDirection());
				salir = true;
			}
		}
		if (!a) {
			//Detección de colisiones
			//System.out.println("WALL·E> 15-M people block your way! Turn around!");
		}
	}
	
	/**
	 * Crea el interprete de instrucciones y el escaner para leer los comandos
	 */
	public void startEngine (){
		boolean salir = false;
		Interpreter interpreter = new Interpreter();
		java.util.Scanner sc = new java.util.Scanner(System.in);
		System.out.println(this.position.toString());
		System.out.println(this.direction.sayDirection());

		while (!salir) {
			System.out.println("");
			System.out.print(ROBOT_NAME + " > ");
			Instruction instruction = interpreter.generateInstruction(sc.nextLine());
			
			if (instruction.isValid()) {
				switch (instruction.getAction()) {
				case MOVE:
					this.move();
					break;
				case TURN:
					this.direction = this.direction.nextDirection(instruction.getRotation());
					System.out.println(this.direction.sayDirection());
					break;
				case HELP: 
					System.out.println(interpreter.interpreterHelp());
					break;
				case QUIT: {
					salir = true; 
					System.out.println(OUTPUT_QUIT);
					break;
				}
				case UNKNOWN: break;
				}
			} else {
				System.out.println(OUTPUT_WRONGCOMMAND);
			}
			
			if (this.position.isSpaceship()){
				System.out.println(OUTPUT_ATSPACESHIP);
				salir = true;
			}
			
		}
		
		sc.close();
	}
	
	//constantes de mensajes a mostrar
	public static final String ROBOT_NAME = "WALL·E";
	private static final String OUTPUT_QUIT = ROBOT_NAME + " says: I have communication problems. Bye bye";
	private static final String OUTPUT_WRONGCOMMAND = ROBOT_NAME + " says: I do not understand. Please repeat";
	private static final String OUTPUT_ATSPACESHIP = ROBOT_NAME + " says: I am at my spaceship. Shutting down... Bye bye";

	
	
	private Place position;
	private Direction direction;
	private Street[] cityMap;
	
}
